<template>
  <div>
    <basic-container>
      <p><b>说明</b>: 请将文件放于{{workSpacePath}}文件夹下,要求存在名为[yyyy-MM-dd]的文件夹，文件夹中的文件格式必须如[2020-12-13_sd_s_region.txt/2020-12-13_sd_d_region.txt]所示，如果未发现要导入的数据请点击刷新或检查文件格式是否符合要求!</p>
    </basic-container>
    <basic-container>
      <div v-if="showRunningTask">
        <h2>正在执行导入 <i class="el-icon-loading"></i></h2>
        <el-row>
        <el-button @click="loadRunningTask" icon="el-icon-refresh">刷新</el-button>
        </el-row>
        <el-row>
          <el-row>
            <el-col span="22">
              <el-table
                :data="runningTask"
                v-loading="runningTaskLoading"
                style="width: 100%">
                <el-table-column
                  prop="date"
                  label="数据时间">
                </el-table-column>
                <el-table-column
                  label="状态"
                  width="180">
                  <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.taskStatus==1">正在运行</el-tag>
                    <el-tag v-if="scope.row.taskStatus==0">等待开始</el-tag>
                    <el-tag type="success" v-if="scope.row.taskStatus==4">创建数据索引</el-tag>
                    <el-tag type="success" v-if="scope.row.taskStatus==5">正在聚合</el-tag>
                    <el-tag type="success" v-if="scope.row.taskStatus==6">攻击分析</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="进度">
                  <template slot-scope="scope">
                    <div v-if="scope.row.taskStatus!=0">
                      <el-progress :percentage="getProgressNum(scope.row)" ></el-progress>
                      {{scope.row.threadTaskProgress.taskProgressCurrent + "/" + scope.row.threadTaskProgress.taskProgressTotal}}
                    </div>
                    <div v-if="scope.row.taskStatus==0">
                      <el-progress percentage="0" ></el-progress>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="taskStartTime"
                  label="任务就绪时间">
                </el-table-column>
                <el-table-column
                  prop="threadTaskProgress.startTime"
                  label="导入开始时间">
                </el-table-column>
                <el-table-column
                  prop="importSFileSize"
                  label="文件大小(S)"
                  :formatter="fileSizeFormatter">
                </el-table-column>
                <el-table-column
                  prop="importSLineNum"
                  label="数据行数(S)"
                  :formatter="getRunningStatusCanGet">
                </el-table-column>
                <el-table-column
                  prop="importDFileSize"
                  label="文件大小(D)"
                  :formatter="fileSizeFormatter">
                </el-table-column>
                <el-table-column
                  prop="importDLineNum"
                  label="数据行数(D)"
                  :formatter="getRunningStatusCanGet">
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-row>
      </div>

      <div v-if="!showRunningTask">
        <h2>可以导入数据</h2>
        <el-row>
          <el-button @click="loadCanImportTaskData" icon="el-icon-refresh">刷新</el-button>
          <el-button icon="el-icon-bottom-right" type="primary" @click.stop="importData">导入</el-button>
        </el-row>
        <el-row>
          <el-col span="22">
            <el-table
              ref="importTable"
              :data="canImportTaskData"
              style="width: 100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                prop="date"
                label="日期">
              </el-table-column>
              <el-table-column
                prop="sfile.name"
                label="文件名(s)">
              </el-table-column>
              <el-table-column
                prop="sfile.fileSize"
                label="文件大小(s)"
                :formatter="fileSizeFormatter">
              </el-table-column>
              <el-table-column
                prop="sfile.lastModifiedTime"
                label="文件最后修改时间(s)">
              </el-table-column>
              <el-table-column
                prop="dfile.name"
                label="文件名(d)">
              </el-table-column>
              <el-table-column
                prop="dfile.fileSize"
                label="文件大小(d)"
                :formatter="fileSizeFormatter">
              </el-table-column>
              <el-table-column
                prop="dfile.lastModifiedTime"
                label="文件最后修改时间(d)">
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

      </div>

      <div>
        <h2>数据已存在</h2>
        <el-row>
          <el-button @click="loadDataImportedTask" icon="el-icon-refresh">刷新</el-button>
        </el-row>
        <el-row>
          <el-col span="22">
            <el-table
              :data="importedTaskData"
              style="width: 100%">
              <el-table-column
                prop="date"
                label="日期">
              </el-table-column>
              <el-table-column
                prop="sfile.name"
                label="文件名(s)">
              </el-table-column>
              <el-table-column
                prop="sfile.fileSize"
                label="文件大小(s)"
                :formatter="fileSizeFormatter">
              </el-table-column>
              <el-table-column
                prop="sfile.lastModifiedTime"
                label="文件最后修改时间(s)">
              </el-table-column>
              <el-table-column
                prop="dfile.name"
                label="文件名(d)">
              </el-table-column>
              <el-table-column
                prop="dfile.fileSize"
                label="文件大小(d)"
                :formatter="fileSizeFormatter">
              </el-table-column>
              <el-table-column
                prop="dfile.lastModifiedTime"
                label="文件最后修改时间(d)">
              </el-table-column>


              <el-table-column
                label="操作"
                width="100">
                <template slot-scope="scope">
                  <el-button @click="deleteFile(scope.row)" type="text" size="small">删除文件</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>

    </basic-container>
  </div>
</template>

<script>
import {getSysParam} from "@/youan/api/system/blade";
import {
  getRunningTaskStatus,
  startImport,
  getDataHasImportedTaskData,
  deleteTaskDataFile,
  getCanImportTaskData
} from "@/youan/api/audit/import";

export default {
  data() {
    return {
      workSpacePath: "",

      canImportTableData: [],
      tableHasExistsTableData: [],
      taskDataList: [],

      showRunningTask: false,
      runningTaskLoading: false,
      runningTask: [],

      importedTaskData: [],
      canImportTaskData: [],
    }
  },
  created() {
    getSysParam("data_import_path").then(resp => {
      this.workSpacePath = resp.data.data;
    })

    this.loadRunningTask();
    this.loadDataImportedTask();
    this.loadCanImportTaskData();
  },
  methods: {
    loadRunningTask() {
      getRunningTaskStatus().then(resp => {
        this.runningTask = resp.data.data;
        this.showRunningTask = this.runningTask.length != 0;
        if(!this.showRunningTask) {
          this.loadCanImportTaskData();
        }
      })
    },
    // 加载数据已经导入，可以删除文件的TaskData
    loadDataImportedTask() {
      getDataHasImportedTaskData().then(resp => {
        this.importedTaskData = resp.data.data;
      })
    },
    // 加载可以导入的TaskData
    loadCanImportTaskData() {
      getCanImportTaskData().then(resp => {
        this.canImportTaskData = resp.data.data;
      })
    },


    deleteFile(row) {
      const message = `此操作将删除工作区(${this.workSpacePath})内的文件[${row.sfile.name}]及[${row.dfile.name}], 是否继续?`;

      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTaskDataFile(row.date).then(resp => {
          this.$message.success("删除文件成功!!");
          this.loadDataImportedTask();
        })
      });
    },
    fileSizeFormatter(row, column, cellValue, index) {
      if(row.taskStatus == 0) {
        return "尚未运行";
      }
      const size = Math.trunc(cellValue / 1024 / 1024);
      return size + " MB";
    },
    getRunningStatusCanGet(row, column, cellValue, index) {
      if(row.taskStatus == 0) {
        return "尚未运行";
      }
      return cellValue;
    },

    getProgressNum(row) {
      const status = row.threadTaskProgress.taskStatus
      if(status == 0) {
        return 0;
      }else if(status == 1) {
        const value = row.threadTaskProgress.taskProgressCurrent/row.threadTaskProgress.taskProgressTotal*100;
        return Math.trunc(value * 0.8);
      }else if(status == 2) {
        return 100;
      }else if(status == 4) {
        return 90;
      }else if(status == 5) {
        return 95;
      }else {
        return 100;
      }
    },
    async importData() {
      function sleep(millisecond) {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve()
          }, millisecond)
        })
      }

      const selected = this.$refs.importTable.selection;
      if (selected.length == 0) {
        this.$message.error("请选择要导入数据的日期!!");
        return;
      }
      const reqData = Array.from(new Set(selected.map(item => item.date)));
      await startImport(reqData);
      this.showRunningTask = true;
      this.runningTaskLoading = true;
      while (this.runningTaskLoading) {
        const resp = await getRunningTaskStatus();
        this.runningTask = resp.data.data;
        this.runningTaskLoading = resp.data.data.length == 0;
        await sleep(3000);
      }
    },
  }
}
</script>

<style scoped>

</style>
